const key = 'userinfo';
module.exports = {
  param(field, defaultValue) {
    const v = this.post(field) || this.get(field);
    if (v === undefined) {
      return defaultValue;
    }
    return v;
  },
  trimValue(field, defaultValue = '') {
    return this.param(field, defaultValue).trim();
  },
  intVal(field, defaultValue) {
    return parseInt(this.param(field, defaultValue));
  },
  doubleVal(field, defaultValue) {
    return parseFloat(this.param(field, defaultValue));
  },
  setLoginUser(userinfo) {
    return this.service('jwt').sign(userinfo);
  },
  getUserId() {
    return this.getLoginUser('id');
  },
  getPlatformId() {
    return this.getLoginUser('platform_id');
  },
  getLoginUser(field = '') {
    const token = think.ctx.header['x-token'];
    if (!token) {
      return null;
    }
    const data = this.service('jwt').unsign(token);
    if (!data) {
      return null;
    }
    if (!field) {
      return data;
    }
    return data[field];
  },
  validUser() {
    const user = this.getLoginUser();
    if (think.isEmpty(user)) {
      think.throw('请先登录', 202);
    }
  }
};
